package com.yhy.wxzn.wcs.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import com.yhy.wxzn.common.enums.WcsDeviceTypeEnums;
import com.yhy.wxzn.common.utils.SpringUtil;
import com.yhy.wxzn.wcs.device.plc.task.PlcTaskThread;
import com.yhy.wxzn.wcs.device.rgv.bean.Node;
import com.yhy.wxzn.wcs.device.rgv.enums.NodeType;
import com.yhy.wxzn.wcs.entity.TaskGenerateRequest;
import com.yhy.wxzn.wcs.entity.WcsDeviceInfo;
import com.yhy.wxzn.wcs.entity.WcsTask;
import com.yhy.wxzn.wcs.enums.PlcTaskProgress;
import com.yhy.wxzn.wcs.enums.TaskStatus;
import com.yhy.wxzn.wcs.enums.TaskType;
import com.yhy.wxzn.wcs.service.IWcsTaskService;
import com.yhy.wxzn.wcs.service.impl.WcsDeviceInfoServiceImpl;
import com.yhy.wxzn.wcs.service.impl.WcsMapInfoServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: wcs_task
 * @Author: jeecg-boot
 * @Date:   2024-01-23
 * @Version: V1.0
 */
@Api(tags="wcs_task")
@RestController
@RequestMapping("/wcs/wcsTask")
@Slf4j
public class WcsTaskController extends JeecgController<WcsTask, IWcsTaskService> {
	@Autowired
	private IWcsTaskService wcsTaskService;


	 @Autowired
	 private WcsDeviceInfoServiceImpl wcsDeviceInfoService;


	 @Autowired
	 private WcsMapInfoServiceImpl mapInfoService;

	/**
	 * 分页列表查询
	 *
	 * @param wcsTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "wcs_task-分页列表查询")
	@ApiOperation(value="wcs_task-分页列表查询", notes="wcs_task-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(WcsTask wcsTask,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<WcsTask> queryWrapper = QueryGenerator.initQueryWrapper(wcsTask, req.getParameterMap());
		Page<WcsTask> page = new Page<WcsTask>(pageNo, pageSize);
		IPage<WcsTask> pageList = wcsTaskService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param wcsTask
	 * @return
	 */
	@AutoLog(value = "wcs_task-添加")
	@ApiOperation(value="wcs_task-添加", notes="wcs_task-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody WcsTask wcsTask) {
		wcsTaskService.save(wcsTask);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param wcsTask
	 * @return
	 */
	@AutoLog(value = "wcs_task-编辑")
	@ApiOperation(value="wcs_task-编辑", notes="wcs_task-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody WcsTask wcsTask) {
		wcsTaskService.updateById(wcsTask);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "wcs_task-通过id删除")
	@ApiOperation(value="wcs_task-通过id删除", notes="wcs_task-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		wcsTaskService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "wcs_task-批量删除")
	@ApiOperation(value="wcs_task-批量删除", notes="wcs_task-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.wcsTaskService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "wcs_task-通过id查询")
	@ApiOperation(value="wcs_task-通过id查询", notes="wcs_task-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		WcsTask wcsTask = wcsTaskService.getById(id);
		if(wcsTask==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(wcsTask);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param wcsTask
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WcsTask wcsTask) {
        return super.exportXls(request, wcsTask, WcsTask.class, "wcs_task");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WcsTask.class);
    }



	 @GetMapping(value = "/taskType")
	 public Result<?> taskType() {
		 ArrayList<Map<Integer,String>> res = new ArrayList<>();
		 for (TaskType value : TaskType.values()) {
			 HashMap<Integer, String> map = new HashMap<>();
			 map.put(value.getTypeNum(),value.getDescription());
			 res.add(map);
		 }
		 return Result.OK(res);
	 }

	 @GetMapping(value = "/rgvs")
	 public Result<?> rgvs() {
		 ArrayList<Map<Integer,String>> res = new ArrayList<>();
		 List<WcsDeviceInfo> collect = SpringUtil.getBean(WcsDeviceInfoServiceImpl.class).list().stream().filter(wcsDeviceInfo -> wcsDeviceInfo.getDeviceType().equals(WcsDeviceTypeEnums.FWV.getValue())).collect(Collectors.toList());
		 for (WcsDeviceInfo  deviceInfo: collect) {
			 HashMap<Integer, String> map = new HashMap<>();
			 map.put(deviceInfo.getId(),deviceInfo.getDeviceName());
			 res.add(map);
		 }

		 return Result.OK(res);
	 }


	 @PostMapping(value = "/generateTask")
	 public Result<?> generateTask(TaskGenerateRequest taskGenerateRequest) {
		 Result result;
		 if ((result = checkParam(taskGenerateRequest)) != null)
			 return result;

		 return wcsTaskService.generateTask(taskGenerateRequest);
	 }

	 private Result checkParam(TaskGenerateRequest req) {

		 if (!StrUtil.isEmpty(req.getStartNodeStr())){
			 try {
				 Node.parseCoord(req.getStartNodeStr());
			 }catch (Exception e){
				 return Result.error("起点,"+e.getMessage());
			 }
		 }


		 if (!StrUtil.isEmpty(req.getEndNodeStr())){
			 try {
				 Node.parseCoord(req.getEndNodeStr());
			 }catch (Exception e){
				 return Result.error("终点,"+e.getMessage());
			 }
		 }

		 if (req.isSystemAssignedMode())
			 return Result.error("暂不支持自动分配小车");


		 if (req.getRgvId() == null ||  wcsDeviceInfoService.getById(req.getRgvId()) == null)
			 return Result.error("小车id为空或小车不存在");

		 if (req.getTaskType() == null)
			 return Result.error("任务类型不能为空");


		 if (TaskType.IN.getTypeNum() == req.getTaskType())
			 return Result.error("暂不支持入库任务");

		 if (TaskType.OUT.getTypeNum() == req.getTaskType())
			 return Result.error("暂不支持出库任务");


		 if ((TaskType.MOVE_UNLOADED.getTypeNum() == req.getTaskType()
				 ||TaskType.CHARGE.getTypeNum() == req.getTaskType()
				 ||TaskType.MOVE_LOADED.getTypeNum() == req.getTaskType()
				 ||TaskType.TRANSFER.getTypeNum() == req.getTaskType())
				 && StrUtil.isEmpty(req.getEndNodeStr()))
			 return Result.error(String.format("任务类型：%s，终点不能为空"
					 ,TaskType.parseTaskType(req.getTaskType()).getDescription()));

		 if (TaskType.TRANSFER.getTypeNum() == req.getTaskType() && StrUtil.isEmpty(req.getStartNodeStr()))
			 return Result.error(String.format("任务类型：%s，起点不能为空"
					 ,TaskType.parseTaskType(req.getTaskType()).getDescription()));



		 if (TaskType.MOVE_STATION.getTypeNum() == req.getTaskType()){
			 Node s = mapInfoService.getNode(Node.parseNode(req.getStartNodeStr()));
			 if (!s.getNodeType().equals(NodeType.ST))
				 return Result.error(String.format("工位行驶任务起点%s的类型不为工位",s.toString()));
			 Node e = mapInfoService.getNode(Node.parseNode(req.getEndNodeStr()));
			 if (!e.getNodeType().equals(NodeType.ST))
				 return Result.error(String.format("工位行驶任务终点%s的类型不为工位",e.toString()));
		 }


		 if (TaskType.LIFTER_TASK.getTypeNum() == req.getTaskType()){
			 Node s = mapInfoService.getNode(Node.parseNode(req.getStartNodeStr()));
			 if (!s.getNodeType().equals(NodeType.L))
				 return Result.error(String.format("提升机任务起点%s的类型不为提升机",s.toString()));
			 Node e = mapInfoService.getNode(Node.parseNode(req.getEndNodeStr()));
			 if (!e.getNodeType().equals(NodeType.L))
				 return Result.error(String.format("提升机任务终点%s的类型不为提升机",e.toString()));
		 }


		 return null;

	 }




	 @PostMapping(value = "/interceptPLC/{taskId}")
	 public Result<?> interceptPLC(@PathVariable Integer taskId) {


		 PlcTaskThread.interceptPLC(taskId);
		 return Result.OK();
	 }


	 @PostMapping(value = "/refreshPLC/{taskId}")
	 public Result<?> refreshPLC(@PathVariable Integer taskId) {

		 if (PlcTaskThread.noNeedForRecoveryPLC(taskId))   return Result.error("正在执行的PLC的任务，不需要恢复");

		 WcsTask task = wcsTaskService.getById(taskId);

		 if (task == null) return Result.error("不存在的任务，不需要恢复");

		 if(task.getTaskType() != TaskType.IN && task.getTaskType() != TaskType.OUT) return Result.error("不为出库或入库任务，不需要恢复");

		 if (task.getTaskStatus() != TaskStatus.ERROR) return  Result.error("不是错误的任务，不需要恢复");

		 if (task.getPlcProgress() != null && task.getPlcProgress() == PlcTaskProgress.ALL_DEVICE_COMPLETE.getTaskProgress())    return Result.error("PLC任务执行完毕的，不需要恢复");


		 wcsTaskService.updateTaskStatus(task,TaskStatus.WAIT);
		 PlcTaskThread.executeTask(task);
		 return Result.OK();
	 }

 }
